package edu.uwm.universitydb.controller;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JComboBox;

import edu.uwm.universitydb.authenticaion.AuthenticationHelper;
import edu.uwm.universitydb.model.Role;
import edu.uwm.universitydb.model.User;
import edu.uwm.universitydb.service.ServiceFactory;
import edu.uwm.universitydb.service.user.UserService;
import edu.uwm.universitydb.swing.UserTableModel;
import edu.uwm.universitydb.view.UserMaint;

public class UserMaintController implements MouseListener {
	
	public UserMaintController() {
		_userService = ServiceFactory.getInstance().getUserService();
		// Create our associated view
		_view = new UserMaint(new UserTableModel(_userService));
		
		// Setup our listeners
		_view.getAddButton().addMouseListener(this);
		_view.getDelButton().addMouseListener(this);

	}
	
	private void onAddButtonClick() {
		//Dummy values
		String name= "";
		Role  role =  null;
		String password = "";
		//Show Edit User View
		JPanel panel = _view.showNewView();
		boolean validated = false;
		while (!validated) {
			int result = JOptionPane.showConfirmDialog(_view, panel, "Add", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
			if (result == JOptionPane.OK_OPTION) {
				//Get user inputs
				for( Component c : panel.getComponents()) {
					if (UserMaint.NAMEFIELD.equals(c.getName())) {
						name = ((JTextField)c).getText();
	                                   } else if  (UserMaint.PASSWORDFIELD.equals(c.getName())) {
                                               password = ((JTextField)c).getText();
                                       } else if  (UserMaint.ROLEFIELD.equals(c.getName())) {
						role = (Role)(((JComboBox<?>)c).getSelectedItem());
					}
				}
				// Add User
				boolean status = _userService.createUser(new User(name,role), password);
				if (status == false) {
					JOptionPane.showMessageDialog(_view, "Error adding user!");
				} else {
					validated = true;
				}
			} else {
				//User cancelled add
				break;
			}
			_view.refreshTable();
		}
	}
	
	/*private void onEditButtonClick() {
		JTable dataTable =  _view.getDataTable();
		//A single row needs to be selected
		int numRows = dataTable.getSelectedRowCount();
		if( numRows == 0 || numRows > 1) {
			JOptionPane.showMessageDialog(_view, "Please select a single row to Edit!");
		} else {
			//Show Edit User View
			String id = (String) dataTable.getValueAt(dataTable.getSelectedRow(), 0);
			User user =  _userService.searchUserByID(id);
			String name = user.getUserName();
			Role  role = user.getRole();

			//Show Edit User View
			JPanel panel = _view.showMaintView(name, role);
			boolean validated = false;
			while (!validated) {
				int result = JOptionPane.showConfirmDialog(_view, panel, "Edit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
				if (result == JOptionPane.OK_OPTION) {
					//Get user inputs
					for( Component c : panel.getComponents()) {
						if (UserMaint.NAMEFIELD.equals(c.getName())) {
							name = ((JTextField)c).getText();
						} else if  (UserMaint.ROLEFIELD.equals(c.getName())) {
							role = (Role)(((JComboBox<?>)c).getSelectedItem());
						}
					}
					// Add User
					boolean status = _userService.updateUser(name, role);
					if (status == false) {
						JOptionPane.showMessageDialog(_view, "Error editing user!");
					} else {
						validated = true;
					}
				} else {
					//User cancelled edit
					break;
				}
				_view.refreshTable();
			}
			
		}
	} */
	
	private void onDelButtonClick() {
		JTable dataTable = _view.getDataTable();
		int numRows = dataTable.getSelectedRowCount();
		
		//At least 1 row needs to be selected
		if (numRows == 0) {
			JOptionPane.showMessageDialog(_view, "Please select row/s to Delete!");
		} else {
			//Confirm delete
			int confirm = JOptionPane.showConfirmDialog(_view,
					"Are you sure you want to delete?", "Confirm", JOptionPane.YES_NO_OPTION);
			if (confirm == JOptionPane.YES_OPTION) {
				List<String> selectedKeys = new ArrayList<String>();
				boolean status = true;
				for (int i : dataTable.getSelectedRows()) {
					String keyVal = (String)dataTable.getValueAt(i, 0);
					selectedKeys.add(keyVal);
				}
				//Perform Delete
				for (String key : selectedKeys) {
					String username = AuthenticationHelper.getUserName();
					if(key.equals(username)) {
						JOptionPane.showMessageDialog(_view, "Cannot delete logged in user!");
						break;
					}
					status = _userService.deleteUser(key);
					if (status == false) {
						JOptionPane.showMessageDialog(_view, "Internal error deleting user!");
						break;
					}
				}
				dataTable.clearSelection();
				_view.repaint();
			}
		}
	}
	
	public UserMaint getView() {
		return _view;
	}
	
	
	@Override
	public void mouseClicked(MouseEvent e) {
		//Based on the element clicked, fire off appropriate handler method.
		switch(e.getComponent().getName()) {
			/*case UserMaint.EDITBUTTON: 
				this.onEditButtonClick();
				break;*/
			case UserMaint.DELBUTTON: 
				this.onDelButtonClick();
				break;
			case UserMaint.ADDBUTTON: 
				this.onAddButtonClick();
				break;
			default: 
				//Not sure what they clicked, do nothing
				break;
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// Unused		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// Unused
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// Unused
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// Unused
	}	
	

	private UserMaint _view;
	
	private UserService _userService;
	
	public static final String ID = "UserMnt";
}
